package fr.cephb.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/** Extends HttpServletResponseWrapper and redirect the response of a servlet to a file */
public class ServletResponseToFile extends HttpServletResponseWrapper {
	
	private File file;
	private PrintWriter w=null;
	private DelegateServletOutputStream out=null;
	

	
	
	public ServletResponseToFile(HttpServletResponse response)
		{
		super(response);
		}
	
	@Override
	public ServletOutputStream getOutputStream() throws IOException {
		System.err.println("Invoked getOutputStream");
		if(this.out==null)
			{
			if(this.file==null)
				{
				this.file= File.createTempFile("ceph_", ".tmp");
				}
			this.out= new DelegateServletOutputStream(new FileOutputStream(this.file));
			}
		return this.out;
		}
	
	@Override
	public PrintWriter getWriter() throws IOException
		{
		if(w==null)
			{
			this.w= new PrintWriter(getOutputStream());
			}
		return this.w;
		}
	
	/** closes the stream used for the redirection */
	public void close() throws IOException
		{
		if(this.w!=null) { w.flush();}
		if(this.out!=null) {out.flush(); out.close();}
		}
	
	/** get the file where the output was redirected */
	public File getFile()
		{
		return this.file;
		}
}
